package com.schoolhelper.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.schoolhelper.constant.Api;
import com.schoolhelper.constant.Variable;
import com.schoolhelper.dao.TUserDao;
import com.schoolhelper.entity.TUser;
import com.schoolhelper.model.EncryptionI;
import com.schoolhelper.model.Md5Encryption;
import com.schoolhelper.model.MyToken;
import com.schoolhelper.service.TUserService;
import com.schoolhelper.utils.MySymmetricEncryption;
import com.schoolhelper.utils.MyRedis;
import com.schoolhelper.vo.UserFollowerVo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (TUser)表服务实现类
 *
 * @author makejava
 * @since 2021-04-23 21:03:36
 */
@Service("tUserService")
public class TUserServiceImpl extends ServiceImpl<TUserDao, TUser> implements TUserService {
    @Autowired
    TUserDao tUserDao;
    private WebTarget target;

    private MyRedis myRedis = new MyRedis();

    public static String LOGIN_ERROR = null;


    /**
     * 登录状态
     *
     * @param token 令牌
     * @return {@link String}
     */
    @Override
    public String getLoginState(String token) {
        return myRedis.get(token);
    }

    /**
     * 退出登录
     *
     * @param token 令牌
     * @return {@link String}
     */
    @Override
    public String loginQuit(String token) {
        myRedis.remove(token);
        return "ok";
    }

    @Override
    @SneakyThrows
    public boolean registerInHx(String username, String password) {
        Client client = ClientBuilder.newBuilder().build();
        target = client.target(Api.BASE_HXURL);

        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("username", username);
        requestBody.put("password", password);
        Response response = target.path(Api.HX_USER)
                .request(MediaType.APPLICATION_JSON)
                .header("Authorization", Variable.HX_TOKEN)
                .post(Entity.entity(requestBody, MediaType.APPLICATION_JSON));
        System.out.println(response.toString());
        return response.getStatus() >= 200 && response.getStatus() < 300;
    }

    @Override
    public TUser getByUsername(String username) {
        List<TUser> userByUsername = tUserDao.getUserByCondition(null, username, null, null, null, null, null, null);
        System.out.println("根据username的查询结果:" + userByUsername);
        try {
            return userByUsername.get(0);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public TUser getByPhone(String phone) {
        List<TUser> userByPhone = tUserDao.getUserByCondition(null, null, null, null, null, phone, null, null);
        System.out.println("根据phone的查询结果:" + userByPhone);
        try {
            return userByPhone.get(0);
        } catch (Exception e) {
            return null;
        }
    }

    @SneakyThrows
    @SuppressWarnings("unchecked")
    public String login(String phone, String password) {
//        // 0代密码
//        List<TUser> userList = tUserDao.queryAll(null, username, password,
//                null, null, null, null, null);
//        if (userList.isEmpty()) {
//            // 1代密码
//            String passwordGeneration1 = MySymmetricEncryption.decrypt(password);
//            userList = tUserDao.queryAll(null, username, passwordGeneration1,
//                    null, null, null, null, null);
//            if (userList.isEmpty()) {
//                // 2代密码
//                String passwordGeneration2 = MySymmetricEncryption.encrypt(password);
//                userList = tUserDao.queryAll(null, username, passwordGeneration2,
//                        null, null, null, null, null);
//            }
//        }

        // 2代密码
        String passwordGeneration2 = MySymmetricEncryption.encrypt(password);
        List<TUser> userList = tUserDao.queryAll(null, null, passwordGeneration2,
                null, null, phone, null, null);
        if (userList.isEmpty()) {
            // 0代密码
            String passwordGeneration1 = MySymmetricEncryption.decrypt(password);
            userList = tUserDao.queryAll(null, null, passwordGeneration1,
                    null, null, phone, null, null);
            if (userList.isEmpty()) {
                // 1代密码
                userList = tUserDao.queryAll(null, null, password,
                        null, null, phone, null, null);
            }

        }

        if (userList.isEmpty()) {
            return LOGIN_ERROR;
        } else {
            TUser user = userList.get(0);
            String userValue = new ObjectMapper().writeValueAsString(user);
            EncryptionI encryptionI = new Md5Encryption();
            String token = MyToken.generateToken(phone, encryptionI);
            myRedis.save(token, userValue);
            System.out.println("redis save the token: " + token);
            System.out.println("value is : " + userValue);

            return token;
        }
    }

    @Override
    public List<UserFollowerVo> getUserFollower(Integer userId) {
        List<UserFollowerVo> userFollower = tUserDao.getUserFollower(userId);
        System.out.println(userFollower);
        return tUserDao.getUserFollower(userId);
    }


}
